package com.second.controller.pay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.second.config.AliPayConfig;
import com.second.service.IFCouponUserService;
import com.second.service.IFOrdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static com.second.config.AliPayConfig.*;


@Controller
@RestController
@RequestMapping("")
public class AliPayController {

    @Autowired
    private IFOrdService ordService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IFCouponUserService couponUserService;

    //订单号/价格/商品名称/描述
    @GetMapping("/aliPay/{orderId}/{amount}/{product}/{body}")
    public String aliPay(@PathVariable String orderId,
                         @PathVariable String amount,
                         @PathVariable String product,
                         @PathVariable String body,
                         HttpServletRequest request) throws AlipayApiException {


        request.setAttribute("orderId", orderId);
        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.GATEWAY_URL,
                AliPayConfig.APP_ID,
                AliPayConfig.APP_PRIVATE_KEY,
                "json",
                CHARSET,
                ALIPAY_PUBLIC_KEY,
                SIGN_TYPE);
//        page
        AlipayTradePagePayRequest alipayPageRequest = new AlipayTradePagePayRequest();
        alipayPageRequest.setReturnUrl(AliPayConfig.RETURN_URL);
        alipayPageRequest.setNotifyUrl(AliPayConfig.NOTIFY_URL);


        //拼接参数
        alipayPageRequest.setBizContent("{\"out_trade_no\":\"" + orderId + "\","
                + "\"total_amount\":\"" + amount + "\","
                + "\"subject\":\"" + product + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        return alipayClient.pageExecute(alipayPageRequest).getBody();
    }

//    @PostMapping("/return")  // 注意这里必须是POST接口
//    public String payReturn(HttpServletRequest request) throws Exception {
//        return "jsp/personal/personal-center";
//    }

    @RequestMapping("/returnUrl")
    public ModelAndView returnUrlMethod(HttpServletRequest request, HttpSession session,
                                        HttpServletResponse response) throws AlipayApiException, IOException {
        System.out.println("=================================同步回调=====================================");
        ModelAndView modelAndView = new ModelAndView();
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println("params:"+params);//查看参数都有哪些
        //验证签名（支付宝公钥）
//        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
//        System.out.println(signVerified);
        //验证签名通过
//        if(signVerified){
            // 商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

        // 支付宝交易流水号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

        // 付款金额
        float money = Float.parseFloat(new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8"));

        System.out.println("商户订单号="+out_trade_no);
        System.out.println("支付宝交易号="+trade_no);
        System.out.println("付款金额="+money);

        //在这里编写自己的业务代码（对数据库的操作）
        ordService.changeOrdUsed(out_trade_no);

        String couponId = (String) redisTemplate.opsForValue().get(out_trade_no);
        if (null!=couponId){
            couponUserService.changeCouponStatusUsed(Integer.valueOf(couponId));
        }


        modelAndView.setViewName("jsp/order/order");
        return  modelAndView;

    }


}
